#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Agent系统入口模块

负责启动和管理整个agent系统。
"""

import asyncio
import logging
import signal
import sys
from typing import Optional

from .agent_core import AgentCore

# 配置日志
logging.basicConfig(
    level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)


class AgentSystem:
    """Agent系统类"""

    def __init__(self, host: str = "0.0.0.0", port: int = 9000):
        """
        初始化Agent系统

        Args:
            host: MCP服务器主机地址
            port: MCP服务器端口
        """
        self.agent_core = AgentCore(host=host, port=port)
        self.loop: Optional[asyncio.AbstractEventLoop] = None

    async def start(self):
        """启动Agent系统"""
        try:
            logger.info("正在启动Agent系统...")
            await self.agent_core.start()
            logger.info("Agent系统已启动")
        except Exception as e:
            logger.error(f"启动Agent系统失败: {e}")
            await self.stop()
            raise

    async def stop(self):
        """停止Agent系统"""
        try:
            logger.info("正在停止Agent系统...")
            await self.agent_core.stop()
            logger.info("Agent系统已停止")
        except Exception as e:
            logger.error(f"停止Agent系统时出错: {e}")
        finally:
            if self.loop and self.loop.is_running():
                self.loop.stop()

    def _handle_signal(self, signum, frame):
        """处理系统信号"""
        logger.info(f"收到信号 {signum}，准备关闭系统...")
        asyncio.create_task(self.stop())


async def main():
    """主函数"""
    # 创建系统实例
    system = AgentSystem()
    system.loop = asyncio.get_running_loop()

    # 注册信号处理器
    for sig in (signal.SIGTERM, signal.SIGINT):
        system.loop.add_signal_handler(
            sig, lambda s=sig: system._handle_signal(s, None)
        )

    try:
        # 启动系统
        await system.start()
    except KeyboardInterrupt:
        logger.info("收到键盘中断，准备关闭系统...")
    except Exception as e:
        logger.error(f"系统运行出错: {e}")
    finally:
        await system.stop()


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        logger.info("程序已终止")
        sys.exit(0)
    except Exception as e:
        logger.error(f"程序异常退出: {e}")
        sys.exit(1)
